(async function () {
  const resp = await API.profile();
  const user = resp.data;

  if (!user) {
    alert("未登录或登陆已过期，请重新登陆");
    return (location.href = "./login.html");
  }

  // 登陆状态
  const doms = {
    aside: {
      nickname: $("#nickname"),
      loginId: $("#loginId"),
    },
    close: $(".close"),
    chatContainer: $(".chat-container"),
    txtMsg: $("#txtMsg"),
    msgContainer: $(".msg-container"),
  };

  // 注销
  doms.close.onclick = function () {
    API.loginOut();
    return (location.href = "./login.html");
  };

  // 加载历史记录
  loadHistory();
  async function loadHistory() {
    const resp = await API.getHistory();
    for (const item of resp.data) {
      addChat(item);
    }
    scrollBottom();
  }

  // 设置个人信息
  setProfile();
  function setProfile() {
    // 不能使用innerHTML, 如果用户输入的<script>alert(1)</script>会被注入攻击
    // 对于用户输入的一律按文本处理
    doms.aside.nickname.innerText = user.nickname;
    doms.aside.loginId.innerText = user.loginId;
  }

  // 发送消息
  async function sendChat() {
    const content = doms.txtMsg.value.trim();
    if (!content) {
      return;
    }
    // 用户体验: 先往页面上添加内容, 不要等待网络结果后在将发送的内容添加到页面上
    addChat({
      from: user.loginId,
      to: null,
      content,
      createdAt: Date.now(),
    });
    doms.txtMsg.value = "";
    scrollBottom();
    const resp = await API.sendChat(content);
    addChat({
      from: null,
      to: user.loginId,
      ...resp.data,
    });
    scrollBottom();
  }
  doms.msgContainer.onsubmit = function (e) {
    e.preventDefault();
    sendChat();
  };

  // 添加消息
  function addChat(chatInfo) {
    const isMe = !!chatInfo.from;

    const msgItem = $$$("div");
    msgItem.className = isMe ? "chat-item me" : "chat-item";

    const avatar = $$$("img");
    avatar.className = "chat-avatar";
    avatar.src = isMe ? "./asset/avatar.png" : "./asset/robot-avatar.jpg";

    const content = $$$("div");
    content.className = "chat-content";
    content.innerText = chatInfo.content;

    const date = $$$("div");
    date.className = "chat-date";
    date.innerText = formateDate(chatInfo.createdAt);

    msgItem.appendChild(avatar);
    msgItem.appendChild(content);
    msgItem.appendChild(date);
    doms.chatContainer.appendChild(msgItem);
  }

  // 格式化时间前置0
  const padStartZero = (time) => time.toString().padStart(2, "0");

  // 格式化日期
  const formateDate = (timestamp) => {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${padStartZero(
      date.getMonth() + 1
    )}-${date.getDate()} ${padStartZero(date.getHours())}:${padStartZero(
      date.getMinutes()
    )}:${padStartZero(date.getSeconds())}`;
  };

  function scrollBottom() {
    doms.chatContainer.scrollTop = doms.chatContainer.scrollHeight;
  }
})();
